//
//  AddGroupFriendViewController.m
//  QinrenManagers
//
//  Created by easaa on 15/8/26.
//  Copyright (c) 2015年 easaa. All rights reserved.
//

#import "AddGroupFriendViewController.h"

#import "AddHuanxinFriendCell.h"

#import "GroupMemberModel.h"

@interface AddGroupFriendViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSMutableArray *healthGroupMemberArry;
@property (nonatomic,strong) NSMutableArray *workGroupMemberArry;
@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) UITableView *friendTableView;

@end

@implementation AddGroupFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _healthGroupMemberArry = [NSMutableArray array];
    _workGroupMemberArry = [NSMutableArray array];
    
//    [self creatDataSource];
    [self requestForHealthGroupData];
    [self requestForWorkGroupData];
    
    [self creatTableView];
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_H-60, SCREEN_W, 60)];
    
    footView.backgroundColor = [UIColor whiteColor];
    
    UIButton *addButton = [[UIButton alloc]initWithFrame:CGRectMake(30, 20, SCREEN_W-40, 30)];
    
    //    [addButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    addButton.layer.cornerRadius = 5;
    addButton.clipsToBounds = YES;
    [addButton setTitle:@"添加好友" forState:UIControlStateNormal];
    [addButton setBackgroundColor:SkyBluecolor];
    [addButton addTarget:self action:@selector(addFriend) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:addButton];

    [self.view addSubview:footView];
    

}

- (void)creatDataSource {
    
    [self requestForHealthGroupData];
    [self requestForWorkGroupData];
    
    if ([self.groupType isEqualToString:HealthGroup]) {
        _dataSource = _healthGroupMemberArry;
    }
    else {
    
        _dataSource = _workGroupMemberArry;
    }
    
    [self creatTableView];

}

- (void)requestForHealthGroupData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [SVProgressHUD showSuccessWithStatus:@"列表请求中"];
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"employee_id":user.employee_id,
                                 @"pagesize":@"1000",
                                 @"pageindex":@"1"};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.user.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"管家好友的dictonary :%@",[dictionary description]);
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                GroupMemberModel * healthGroupMemberModel = [[GroupMemberModel alloc]init];
                [healthGroupMemberModel setValuesForKeysWithDictionary:dataDic];
                
                for (FriendModel *model in _friendArry) {
                    if ([model.hx_username isEqualToString:healthGroupMemberModel.hx_username]) {
                        healthGroupMemberModel.isHave = YES;
                        break;
                    }
                }
                if (!healthGroupMemberModel.isHave) {
                    [_healthGroupMemberArry addObject:healthGroupMemberModel];
                }
//                [_healthGroupMemberArry addObject:healthGroupMemberModel];

            }
            
            if ([self.groupType isEqualToString:HealthGroup]) {
                _dataSource = [_healthGroupMemberArry copy];
            }
            else {
                
                _dataSource = [_workGroupMemberArry copy];
            }

            [_friendTableView reloadData];
            
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}

- (void)requestForWorkGroupData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [SVProgressHUD showSuccessWithStatus:@"列表请求中"];
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"employee_id":user.employee_id};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"get.manager.employee" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"管家上下级的dictonary :%@",[dictionary description]);
        
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                GroupMemberModel * workGroupMemberModel = [[GroupMemberModel alloc]init];
                [workGroupMemberModel setValuesForKeysWithDictionary:dataDic];
                
                for (FriendModel *model in _friendArry) {
                    if ([model.hx_username isEqualToString:workGroupMemberModel.hx_username]) {
                        workGroupMemberModel.isHave = YES;
                        break;
                    }
                }
                if (!workGroupMemberModel.isHave) {
                    [_workGroupMemberArry addObject:workGroupMemberModel];
                }
//                [_workGroupMemberArry addObject:workGroupMemberModel];
                
            }
            if ([self.groupType isEqualToString:HealthGroup]) {
                _dataSource = [_healthGroupMemberArry copy];
            }
            else {
                
                _dataSource = [_workGroupMemberArry copy];
            }

            [_friendTableView reloadData];
            
            
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}


- (void)creatTableView
{
    _friendTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-60) style:UITableViewStylePlain];
    
    _friendTableView.backgroundColor = Lightlightcolor;
    _friendTableView.delegate = self;
    _friendTableView.dataSource = self;
    _friendTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    UINib * nib = [UINib nibWithNibName:@"AddHuanxinFriendCell" bundle:nil];
    
    [_friendTableView registerNib:nib forCellReuseIdentifier:@"AddHXFriendCell"];
    
    
    [self.view addSubview:_friendTableView];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.dataSource count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddHuanxinFriendCell *cell = [[AddHuanxinFriendCell alloc]init];
    static NSString *CellIdentifier = @"AddHXFriendCell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[AddHuanxinFriendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    if ([self.groupType isEqualToString:HealthGroup]) {
        [cell fillCellWithHealthModel:_dataSource[indexPath.row]];
    }
    else if ([self.groupType isEqualToString:WorkGroup]) {
        [cell fillCellWithWorkModel:_dataSource[indexPath.row]];
    }

    //填充数据
    return cell;
}



#pragma mark - Table view delegate

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//
//    return 60;
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    FriendModel *friendModel = _dataSource[indexPath.row];
    
    friendModel.isSelected = !friendModel.isSelected;
    [self.friendTableView reloadData];
}

- (void)addFriend {
    
    NSMutableArray *firendIDArry = [NSMutableArray array];
    if (_dataSource.count > 0) {
        for(GroupMemberModel * friendModel in _dataSource) {
            if (friendModel.isSelected) {
                [firendIDArry addObject:friendModel.hx_username];
            }
        }
        
        if (firendIDArry.count>0) {
            NSString *friendIDString = [firendIDArry componentsJoinedByString:@","];
            EAHttpAPIClient *manager = [EAHttpAPIClient manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [SVProgressHUD show];
            
            NSDictionary *parameters = @{@"groupid":self.groupID,@"username":friendIDString};
            NSLog(@"%@",parameters);
            [manager GetWithParameters:parameters method:@"set.hxgroup.user" success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSString *resposeString ;
                if ([responseObject isKindOfClass:[NSData class]]) {
                    resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                }else
                    resposeString = responseObject;
                
                NSString *jsonString = [DataParser parseString:resposeString];
                id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
                NSLog(@"添加群好友的dictonary :%@",[dictionary description]);
                
                NSString *error = [dictionary objectForKey:@"error"];
                [SVProgressHUD showInfoWithStatus:error];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
                [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
            }];
            
        }
        else {
            [SVProgressHUD showErrorWithStatus:@"选择不能为空"];
        }
       
    }else {
    
        [SVProgressHUD showErrorWithStatus:@"好友列表为空"];
//        [SVProgressHUD showErrorWithStatus:@"选择不能为空"];
    }
    
//    [self.navigationController popViewControllerAnimated:YES];
    [SVProgressHUD dismiss];

}

@end
